﻿using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;

namespace TowerCraneMonitorClient.NetClient
{
    /// <summary>
    /// 实体助手
    /// </summary>
    public static class EntityHelper
    {
        /// <summary>
        /// 清除 RunDatas 实体中记录，保留最近 reserved 天。未执行上下文.SaveChange()
        /// </summary>
        /// <param name="entities">上下文.RunDatas 属性值</param>
        /// <param name="reserved">保留天数。缺省 30 天</param>
        /// <returns>清除记录数</returns>
        public static int ClearingOverdue(this DbSet<RunData.Entity> entities, int reserved = 30)
        {
            var earlyTime = DateTime.Now - new TimeSpan(reserved, 0, 0, 0);
            var useless = entities.Where(t => t.Time < earlyTime);
            return ClearingOverdue(entities, useless);
        }

        /// <summary>
        /// 清除 EventAlarms 实体及其依赖实体中记录，保留最近 1M 条。未执行上下文.SaveChange()
        /// </summary>
        /// <param name="entities">上下文.EventAlarms 属性值</param>
        /// <param name="reserved">保留记录条数。缺省 100 万条</param>
        /// <returns></returns>
        public static int ClearingOverdue(this DbSet<EventAlarm.Entity> entities, int reserved = 1000_000)
        {
            var useless = entities
                .Include(a => a.EventMessage)
                .Take(entities.Count() - reserved);
            return ClearingOverdue(entities, useless);
        }

        /// <summary>
        /// 清除一般类型实体记录，保留最近 1M 条。未执行上下文.SaveChange()
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="entities">上下文中实体属性</param>
        /// <param name="reserved">保留记录条数。缺省 100 万条</param>
        /// <returns>清除记录数</returns>
        public static int ClearingOverdue<T>(this DbSet<T> entities, int reserved = 1000_000) where T : class
        {
            var useless = entities.Take(entities.Count() - reserved);
            return ClearingOverdue(entities, useless);
        }

        /// <summary>
        /// 清除实体记录
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="entities">上下文中实体属性</param>
        /// <param name="useless">欲清除的实体集合</param>
        /// <returns>清除记录数</returns>
        static int ClearingOverdue<T>(DbSet<T> entities, IQueryable<T> useless) where T : class
        {
            entities.RemoveRange(useless);
            return useless.Count();
        }
    }
}
